package com.chuangke.message.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.message.constant.MsgConstants;
import com.chuangke.message.entity.SysMessage;
import com.chuangke.message.model.Message;
import com.chuangke.message.service.MessageService;
import com.chuangke.message.service.SysMessageService;
import com.chuangke.sms.model.SMSModel;
import com.chuangke.sms.service.SMSService;

import cn.hutool.core.util.StrUtil;

@Service
public class MessageServiceImpl implements MessageService {

	@Autowired
	private SMSService smsService;
	@Autowired
	private SysMessageService sysMessageService;

	@Override
	public void send(List<Message> list) {
		list.forEach(this::send);
	}

	@Override
	public void send(Message message) {
		if (message == null || StrUtil.isBlank(message.getType())) {
			throw new ChuangkeException("消息或消息类型为空，请确认.");
		}

		switch (message.getType()) {
		case Message.TYPE_SMS:
			smsService.send(buildSmsModel(message));
			break;
		case Message.TYPE_MESSAGE:
			sysMessageService.send(Arrays.asList(buildSysMessageModel(message)));
			break;
		default:
			throw new ChuangkeException(String.format("未找到消息类型：[%s]", message.getType()));
		}
	}

	private SMSModel buildSmsModel(Message message) {
		SMSModel model = new SMSModel();
		model.setUserId(message.getToUserId());
		model.setTelphone(message.getToUserTelphone());
		model.setMessage(message.getMessage());
		return model;
	}

	private SysMessage buildSysMessageModel(Message message) {
		SysMessage sysMessage = new SysMessage();
		sysMessage.setId(IdManager.nextId());
		sysMessage.setContent(message.getMessage());
		sysMessage.setId(IdManager.nextId());
		sysMessage.setReceiver(message.getToUserId());
		sysMessage.setSender(message.getFromUserId());
		sysMessage.setSendTime(new Date());
		sysMessage.setStatus(MsgConstants.STATUS_UNREAD);
		sysMessage.setType(MsgConstants.TYPE_NORMAL);

		if (StrUtil.isBlank(message.getFromUserId())) {
			sysMessage.setSender(MsgConstants.SYSTEM_USER);
			sysMessage.setType(MsgConstants.TYPE_SYSTEM);
		}

		return sysMessage;
	}

}
